import type { ElegantConstRoute } from '@elegant-router/types';
import { request } from '../request';

/** 后端返回的路由数据结构 */
interface BackendRouterVo {
  name: string;
  path: string;
  hidden?: boolean;
  redirect?: string;
  component: string;
  query?: string;
  alwaysShow?: boolean;
  meta: {
    title: string;
    icon?: string;
    noCache?: boolean;
    link?: string;
  };
  children?: BackendRouterVo[];
}

/** 将后端路由数据转换为前端路由格式 */
function transformBackendRoute(backendRoute: BackendRouterVo): ElegantConstRoute {
  const frontendRoute: ElegantConstRoute = {
    name: backendRoute.name,
    path: backendRoute.path,
    component: backendRoute.component,
    meta: {
      title: backendRoute.meta.title,
      icon: backendRoute.meta.icon,
      noCache: backendRoute.meta.noCache,
      link: backendRoute.meta.link,
      hideInMenu: backendRoute.hidden || false
    }
  };

  // 处理子路由
  if (backendRoute.children && backendRoute.children.length > 0) {
    frontendRoute.children = backendRoute.children.map(transformBackendRoute);
  }

  return frontendRoute;
}

/** get routes */
export function fetchGetRoutes() {
  return request<BackendRouterVo[]>({ url: '/system/menu/getRouters' }).then(response => {
    if (response.data) {
      // 转换后端路由数据为前端格式
      const transformedRoutes = response.data.map(transformBackendRoute);
      return { data: transformedRoutes, error: null };
    }
    return response;
  });
}
